import gdata.docs.data
import gdata.docs.client
import gdata.spreadsheet.service
import sys, os
from optparse import OptionParser

p = OptionParser()
p.add_option('-u', dest='user', help="Gmail account name")
p.add_option('-p', dest='password', help="Gmail password")
p.add_option('-n', dest='name', help="Account name")
p.add_option('-v', dest='ver', help="Version")
p.add_option('-d', dest='dir', help='Local directory')
p.add_option('-f', dest='pattern', help='A pattern in the filename to match')

(opt, args) = p.parse_args()

if not (opt.user and opt.password and opt.name and opt.ver and opt.dir):
  p.print_help()
  sys.exit(0)

cdoc = gdata.docs.client.DocsClient()
cdoc.ssl = True
cdoc.ClientLogin(email=opt.user, password=opt.password, source='uoit-pages')

# Get the folder
foldername = "pages - %s - %s" % (opt.name, opt.ver)
folder = None
for f in cdoc.GetDocList(uri="/feeds/default/private/full/-/folder").entry:
  if f.title.text == foldername:
    folder = f
    break

if not folder:
  print 'Folder "%s" is not found' % foldername
  sys.exit(0)

for filename in os.listdir(opt.dir):
  if opt.pattern and not (opt.pattern.lower() in filename.lower()):
    continue
  if not filename.endswith('.xls'):
    continue
  path = os.path.join(opt.dir, filename)
  with open(path, 'r') as f:
    print filename, 
    ms = gdata.data.MediaSource(
            file_handle = f,
            content_type = 'application/vnd.ms-excel',
            content_length = os.path.getsize(path))
    cdoc.Upload(ms, filename[:-4],
            folder_or_uri = folder.content.src+"?convert=true")
    print "uploaded"
